var baseUrl = "/weixin/";
var token = window.localStorage.getItem('SHINEHAODISPLAYVIEWTOKEN');
var sizexx = window.localStorage.getItem('SHINEHAOZOOMSIZE');
var size = Number(sizexx === null ? 1 : sizexx);
var date = "";
var month = "";
var vueData = {
  loading: false,
  user: null,
  search: {
    deptWork: [],
    deptWorkName: ''
  },
  deptWorkList: [],
  type: '',
  cascaderProps: {
    value: 'id',
    label: 'name',
    multiple: true
  }
};

var app = new Vue({
  el: '#app-title',
  data: function () {
    vueData.hasTitle = window.parent === window;
    return vueData;
  },
  created: function () {
    this.loading = true;
    var self = this;
    this.setUser().then(function () {
      return self.setDeptWorkList().then(function () {
        return page.getDate(true).then(function () {
          self.loading = false;
        })
      });
    }).catch(function () {
      self.loading = false;
    });
  },
  methods: {
    setUser: function () {
      var self = this;
      return SystemUtil.getUser().then(function (user) {
        self.user = user;
        return user;
      });
    },

    setDeptWorkList: function () {
      var user = this.user;
      var isManager = user.isManager;
      var type;
      if (isManager === 1) {
        type = 'registrar';
      } else {
        var deptId = user.deptId;
        if (deptId === '0') {
          type = 'registrar';
        } else {
          var duty = user.duty;
          if (duty === '1') {
            type = 'manager';
          } else if (duty === '2') {
            var workshopId = user.workShopId;
            if (workshopId === '0') {
              type = 'manager';
            } else {
              type = 'leader';
            }
          } else {
            type = '';
          }
        }
      }
      this.type = type;
      if (type === '') {
        return;
      }
      var self = this;
      return ajaxRequest('basicData/getWorkshop').then(function (deptWorks) {
        var deptWorkList = [];
        if (type === 'registrar') {
          deptWorkList = self.getDeptWorkList(deptWorks);
          self.deptWorkList = deptWorkList;
        } else if (type === 'manager') {
          var deptId = user.deptId;
          deptWorks = _.filter(deptWorks, {
            deptId: deptId
          });
          deptWorkList = self.getWorkshopList(deptWorks);
          self.deptWorkList = deptWorkList;

          if (deptWorkList.length > 0) {
            self.search.deptWorkName = deptWorkList[0].name;
          }
        } else if (type === 'leader') {
          var deptId = user.deptId;
          var workShopId = user.workShopId;
          var deptWork = _.find(deptWorks, {
            deptId: deptId,
            id: workShopId
          });
          if (deptWork) {
            self.search.deptWorkName = `${deptWork.productionLine}-${deptWork.workshopName}`;
            self.search.deptWork = [deptWork.id];
          }
        }
        return deptWorkList;
      });
    },

    getDeptWorkList: function (deptWorks) {
      var deptWorkObj = {};
      for (var i = 0; i < deptWorks.length; i++) {
        var deptWork = deptWorks[i];
        var deptId = `dept_${deptWork.deptId}`;
        var deptName = deptWork.productionLine;
        deptWorkObj[deptId] = {
          id: deptId,
          name: deptName,
          pId: null
        };

        var workshopId = `workshop_${deptWork.id}`;
        var workshopName = deptWork.workshopName;
        deptWorkObj[workshopId] = {
          id: workshopId,
          name: workshopName,
          pId: deptId
        };
      }

      var deptWorkList = [];
      for (const key in deptWorkObj) {
        var deptWork = deptWorkObj[key];
        var parentId = deptWork.pId;
        if (parentId !== null) {
          var parentObj = deptWorkObj[parentId];
          if (!parentObj) {
            continue;
          }
          if (parentObj.children === undefined) {
            parentObj.children = [];
          }
          parentObj.children.push(deptWork);
        } else {
          deptWorkList.push(deptWork);
        }
      }
      return deptWorkList;
    },

    getWorkshopList: function (deptWorks) {
      deptWorkList = _.map(deptWorks, function (deptWork) {
        return {
          id: deptWork.id,
          name: deptWork.workshopName
        };
      });
      return deptWorkList;
    }
  }
});

$(function () {
  page.bind();
  page.zoomTable(size);
});

//十五分钟执行一次
setInterval(function () {
  page.getDate();
}, 900000);

var page = { //页面总变量
  ff: null,
  firstTitle: "01",
  getDate: function (hasAlert) {
    if (hasAlert === undefined) {
      hasAlert = false;
    }

    return ajaxRequest('displayView/getDate', {}, true, hasAlert).then(function (data) {
      date = data.substring(0, 10);
      month = date.substring(0, 7);
      return page.getCapacity(month, hasAlert);
    });
  },
  bind: function () {
    $("#loginOut").bind("click", function () {
      window.localStorage.setItem('SHINEHAODISPLAYVIEWTOKEN', "");
      location.href = baseUrl + 'displayView/loginOut';
    });

    $(window).resize(function () {
      page.rollTable();
      trunoverDuty.rollTable();
    });

    $("#da").bind("click", function () {
      size = size + 0.1;
      page.set(size);
    });

    $("#shaiXuan").bind("click", function () {
      vueData.loading = true;
      page.getDate(true).then(function () {
        vueData.loading = false;
      }).catch(function () {
        vueData.loading = false;
      });
    });

    $("#xiao").bind("click", function () {
      size = size - 0.1;
      if (size <= 0.5) {
        layAlert("不能再缩小了");
        return false;
      }
      page.set(size);
    });
  },
  //根据车间与工序名称获取该车间所有工序产能信息（thArray为工序数组，决定表格头）
  getCapacity: function (month, hasAlert) {
    var deptWork = vueData.search.deptWork;
    var workShopIdList = this.getWorkshopList(deptWork);

    return ajaxRequest('displayView/queryCapacity', {
      month: month,
      token: token,
      autoLogin: "autoLogin",
      workShopIdList: workShopIdList.length === 0 ? '' : JSON.stringify(workShopIdList)
    }, true, hasAlert).then(function (data) {
      var dayTitle = page.getTitle(month, 1);
      var monthDayList = page.getTitle(month, 2);
      var listCapacity = data;

      var beforeArray = new Array();
      var afterArray = new Array();
      var firstTitle = page.firstTitle;
      firstTitle = month + '-' + firstTitle;
      for (var i = 0; i < dayTitle.length; i++) {
        if (firstTitle > dayTitle[i]) {
          beforeArray.push(dayTitle[i]);
        } else {
          afterArray.push(dayTitle[i]);
        }
      }
      dayTitle = afterArray;
      dayTitle = dayTitle.concat(beforeArray);
      //表头
      var html =
        "<tr style='background-color:#8B8989'><th style='width:41px;'>车间</th><th style='width:41px;' class='sumTit'>合计</th><th style='width:46px;'>计划日<br/>产能</th><th style='width:46px;'>月计划<br/>产能</th><th style='width:41px;'>排单<br/>产能</th><th style='width:46px;'>每日实<br/>际产能</th><th style='width:46px;'>产能达<br/>成率</th><th style='width:46px;'>车间周<br/>转量</th>";
      for (var i = dayTitle.length - 1; i >= 0; i--) {
        html += "<th style='min-width:40px;'>" + dayTitle[i].substring(8, 10) + "</th>";
      }
      html += "</tr>";

      //表体
      for (var i = 0; i < listCapacity.length; i++) {
        var sumCapacity = 0; //车间产能和
        var listDuty = listCapacity[i].listDuty; //车间产能明细
        var dayCapacity = listCapacity[i].dayCapacity; //车间日产能

        //月计划产能   : 日产能    * 月工作天数
        var monthPlanCapacity = dayCapacity * page.getMonthWorkDay(listCapacity[i].restType, monthDayList);

        //获取产能合计
        for (var x = 0; x < listDuty.length; x++) { //车间产能之后等于每天产能相加
          sumCapacity = sumCapacity + listDuty[x].capacity;
        }

        //实际上班天数
        var aleradyWorkDay = page.getMonthWorkDay(listCapacity[i].restType, dayTitle);

        //每日实际产能
        if (aleradyWorkDay == 0) {
          aleradyWorkDay = 1;
        }
        var dayReachCapacity = sumCapacity / aleradyWorkDay;
        dayReachCapacity = dayReachCapacity.toFixed(0);

        //获取达成率
        var daChengLv = 0;
        if (dayCapacity * aleradyWorkDay != 0) {
          daChengLv = sumCapacity / (dayCapacity * aleradyWorkDay) * 100;
        } else {
          daChengLv = 0.00;
        }
        daChengLv = daChengLv.toFixed(2);

        //如果日平均产能大于车间日产能底色为绿色  否则为#FFE4B5
        if (sumCapacity / dayTitle.length >= dayCapacity) {
          html += "<tr>";
        } else {
          html += "<tr>";
        }

        html += "<td>" + listCapacity[i].workShopName + "</td><td class='sumTit'><span class='sumCapacity'>" + sumCapacity +
          "</span></td><td>" + dayCapacity + "</td><td>" + monthPlanCapacity + "</td><td>" + listCapacity[i].turnover + "</td><td>" +
          dayReachCapacity + "</td><td>" + daChengLv + "%</td><td>" + listCapacity[i].workShopStartTurnover + "</td>";
        //循环表头
        for (var j = dayTitle.length - 1; j >= 0; j--) {
          var capacity = "0";
          for (var z = 0; z < listDuty.length; z++) {
            //如果此日期有产能，返回产能
            if (listDuty[z].delayTime == dayTitle[j]) {
              capacity = listDuty[z].capacity;
              break;
            }
          }
          //如果当日产能小于日产能  红色显示
          if (capacity >= dayCapacity) {
            html += "<td><span class='capacity'>" + capacity + "</span></td>";
          } else {
            html += "<td><span class='capacity' style='color:red;'>" + capacity + "</span></td>";
          }
        }
        html += "</tr>";
      }
      $("#queryCapacityTable").html(html);
      return trunoverDuty.getTrunoverDutyMantissa(workShopIdList, hasAlert);
    });
  },
  getWorkshopList: function (deptWork) {
    if (deptWork.length === 0) {
      return [];
    }

    var workshopList = [];
    if (_.isArray(deptWork[0])) {
      for (var i = 0; i < deptWork.length; i++) {
        var deptWorks = deptWork[i];
        var workshopId = deptWorks[1];
        workshopId = workshopId.split('_')[1];
        workshopList.push(workshopId);
      }
    } else {
      workshopList = deptWork;
    }
    return workshopList;
  },
  rollTable: function () {
    var tableWidth = $("#queryCapacityTable").width();
    var divWidth = $("#tableDiv").width();
    //已经在滚动了,就不再滚动

    var tableWidth = $("#queryCapacityTable").width();
    var divWidth = $("#tableDiv").width();
    //如果表格宽度大于div的宽度，则需要轮播
    if (tableWidth > divWidth) {
      if (page.ff != null) {
        return false;
      }
      page.ff = setInterval("page.tableScroll()", 4000);
    } else {
      if (page.ff != null) {
        clearInterval(page.ff);
        page.ff = null;
      }
    }
  },
  tableScroll: function () {
    $("#queryCapacityTable tr").each(function () {
      $(this).append($(this).find("td").eq(8));
      $(this).append($(this).find("th").eq(8));
    });
  },
  /**
   * 获取日期表头
   * month 月份
   * type 类型 1 查询当前月到目前为止天数  2 查询当前月总天数
   */
  getTitle: function (month, type) {
    var array = new Array();
    var thisMonth = date.substring(0, 7); //本月分
    var lastDay = 30;
    if (thisMonth == month && type == 1) {
      lastDay = moment(date).date(); //如果是本月分，最后一天是今天
    } else {
      lastDay = moment(month).endOf("month").date(); //否则是当月最后一天
    }
    for (var i = 1; i <= lastDay; i++) {
      var day = "-0";
      if (i < 10) {
        day += i;
      } else {
        day = "-" + i;
      }
      array.push(month + day);
    }
    return array;
  },
  /**
   * restType 休息类型
   * listDay 查询日期集合
   */
  getMonthWorkDay: function (restType, listDay) {
    var workDay = 0; //当月实际工作天数：当月天数减去当月休息天数
    switch (restType) {
      case 0:
        workDay = listDay.length;
        break; //月休0填
      case 1: //月休一天
        var noWorkDay = 0;
        var day = Number(listDay[listDay.length - 1].substring(8, 10));
        if (day > 1) {
          noWorkDay = noWorkDay + 1;
        }
        workDay = listDay.length - noWorkDay;
        break;
      case 2: //月休两天
        var noWorkDay = 0;
        var day = Number(listDay[listDay.length - 1].substring(8, 10));
        if (day > 15) {
          noWorkDay = noWorkDay + 2;
        } else if (day > 1) {
          noWorkDay = noWorkDay + 1;
        }
        workDay = listDay.length - noWorkDay;
        break;
      case 3: //月休三天
        var noWorkDay = 0;
        var day = Number(listDay[listDay.length - 1].substring(8, 10));
        if (day > 20) {
          noWorkDay = noWorkDay + 3;
        } else if (day > 10) {
          noWorkDay = noWorkDay + 2;
        } else if (day > 1) {
          noWorkDay = noWorkDay + 1;
        }
        workDay = listDay.length - noWorkDay;
        break;
      case 4: //周休一天
        var noWorkDay = 0;
        for (var i = 0; i < listDay.length; i++) {
          if (moment(listDay[i]).day() == 0) { //如果是星期天,休息天加1
            noWorkDay = noWorkDay + 1;
          }
        }
        workDay = listDay.length - noWorkDay;
        break;
      case 5: //周休1.5天
        var noWorkDay = 0;
        for (var i = 0; i < listDay.length; i++) {
          if (moment(listDay[i]).day() == 0) { //如果是星期天,休息天加1
            noWorkDay = noWorkDay + 1;
          }
          if (moment(listDay[i]).day() == 6) { //如果是星期6,休息天加0.5
            noWorkDay = noWorkDay + 0.5;
          }
        }
        workDay = listDay.length - noWorkDay;
        break;
      case 6: //周休2天
        var noWorkDay = 0;
        for (var i = 0; i < listDay.length; i++) {
          if (moment(listDay.length[i]).day() == 0 || moment(listDay.length[i]).day() == 6) { //如果是星期天，星期六,休息天加1
            noWorkDay = noWorkDay + 1;
          }
        }
        workDay = listDay.length - noWorkDay;
        break;
    }
    return workDay;
  },
  set: function (size) {
    page.zoomTable(size);
    window.localStorage.setItem('SHINEHAOZOOMSIZE', size);
    page.rollTable();
    trunoverDuty.rollTable();
  },

  zoomTable: function (size) {
    $('.page-container').css('zoom', size);
    $('#app-title').css('zoom', Math.min(1.8, size));
  }
}
